import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../controllers/message_controller.dart';
import '../../../data/constants/alarm_type_icon.dart';
import '../../../routes/app_pages.dart';

class MessageBgView extends StatelessWidget {
  final Widget child;
  const MessageBgView({super.key, required this.child});
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Column(
          children: [
            Container(
              width: double.infinity,
              height: 453.h,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/message/top_bg.png'),
                  fit: BoxFit.cover,
                ),
              ),
            ),
            Expanded(child: Container(color: Color(0xFFEDF3FA))),
          ],
        ),
        Positioned.fill(
          child: SafeArea(
            child: Container(margin: EdgeInsets.only(top: 60.h), child: child),
          ),
        ),
      ],
    );
  }
}

class MessageView extends GetView<MessageController> {
  const MessageView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: MessageBgView(
        child: Column(
          children: [
            // 标签栏 - 与MineView保持一致的padding
            Padding(
              padding: EdgeInsets.only(left: 40.w, right: 40.w),
              child: Obx(
                () => Row(
                  children: [
                    // 告警消息标签
                    GestureDetector(
                      onTap: () => controller.changeTab(0),
                      child: Text(
                        '告警消息',
                        style: TextStyle(
                          fontSize:
                              controller.selectedTabIndex.value == 0
                                  ? 36.sp
                                  : 32.sp,
                          fontWeight:
                              controller.selectedTabIndex.value == 0
                                  ? FontWeight.w500
                                  : FontWeight.normal,
                          color:
                              controller.selectedTabIndex.value == 0
                                  ? const Color(0xFF333333)
                                  : const Color(0xFF666666),
                        ),
                      ),
                    ),
                    SizedBox(width: 72.w),
                    // 未读消息标签（带角标）
                    GestureDetector(
                      onTap: () => controller.changeTab(1),
                      child: Stack(
                        clipBehavior: Clip.none,
                        children: [
                          Text(
                            '未读消息',
                            style: TextStyle(
                              fontSize:
                                  controller.selectedTabIndex.value == 1
                                      ? 36.sp
                                      : 32.sp,
                              fontWeight:
                                  controller.selectedTabIndex.value == 1
                                      ? FontWeight.w500
                                      : FontWeight.normal,
                              color:
                                  controller.selectedTabIndex.value == 1
                                      ? const Color(0xFF333333)
                                      : const Color(0xFF666666),
                            ),
                          ),
                          // 角标 - 使用真实未读数，超过99显示99+
                          if (controller.unreadCount.value > 0)
                            Positioned(
                              top: -25.h,
                              right: -15.w,
                              child: Builder(
                                builder: (context) {
                                  final count = controller.unreadCount.value;
                                  final displayText =
                                      count > 99 ? '99+' : '$count';
                                  final isLarge = count > 99;
                                  return Container(
                                    constraints: BoxConstraints(
                                      minWidth: isLarge ? 28.w : 18.w,
                                      minHeight: 18.h,
                                    ),
                                    padding: EdgeInsets.symmetric(
                                      horizontal: isLarge ? 8.w : 6.w,
                                      vertical: 2.h,
                                    ),
                                    decoration: BoxDecoration(
                                      color: const Color(0xFFFF0202),
                                      borderRadius: BorderRadius.circular(29.r),
                                    ),
                                    child: Center(
                                      child: Text(
                                        displayText,
                                        style: const TextStyle(
                                          fontSize: 10,
                                          fontWeight: FontWeight.w500,
                                          color: Colors.white,
                                        ),
                                      ),
                                    ),
                                  );
                                },
                              ),
                            ),
                        ],
                      ),
                    ),
                    const Spacer(),
                    // 时间筛选按钮
                    GestureDetector(
                      onTap: () => _showDatePicker(),
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 8.h,
                        ),
                        decoration: BoxDecoration(
                          color:
                              controller.isDateFilterEnabled.value
                                  ? const Color(
                                    0xFF127FFF,
                                  ).withValues(alpha: 0.1)
                                  : const Color(0xFFF5F5F5),
                          borderRadius: BorderRadius.circular(16.r),
                          border: Border.all(
                            color:
                                controller.isDateFilterEnabled.value
                                    ? const Color(0xFF127FFF)
                                    : const Color(0xFFE0E0E0),
                            width: 1,
                          ),
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              Icons.calendar_today_outlined,
                              size: 20.sp,
                              color:
                                  controller.isDateFilterEnabled.value
                                      ? const Color(0xFF127FFF)
                                      : const Color(0xFF999999),
                            ),
                            SizedBox(width: 4.w),
                            Text(
                              controller.isDateFilterEnabled.value
                                  ? '${controller.selectedDate.value.month}-${controller.selectedDate.value.day}'
                                  : '筛选',
                              style: TextStyle(
                                fontSize: 24.sp,
                                color:
                                    controller.isDateFilterEnabled.value
                                        ? const Color(0xFF127FFF)
                                        : const Color(0xFF999999),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(width: 16.w),
                    // 一键已读 - 连接真实功能
                    GestureDetector(
                      onTap:
                          controller.isLoading.value
                              ? null
                              : controller.markAllMessagesRead,
                      child: Opacity(
                        opacity: controller.isLoading.value ? 0.5 : 1.0,
                        child: Text(
                          '一键已读',
                          style: TextStyle(
                            fontSize: 26.sp,
                            color: const Color(0xFF127FFF),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(child: _buildMessageList()),
          ],
        ),
      ),
    );
  }

  // 消息列表区域 - 使用真实数据
  Widget _buildMessageList() {
    return Container(
      margin: EdgeInsets.only(top: 10.h),
      child: Obx(() {
        // ✅ 确保所有响应式变量访问都在Obx内部，以便正确触发更新
        final listLength = controller.messageList.length;
        final isLoading = controller.isLoading.value;
        final hasMoreData = controller.hasMoreData.value;
        final selectedTabIndex = controller.selectedTabIndex.value;

        print('🔄 列表构建 - 消息数量: $listLength, 加载中: $isLoading');

        // 如果没有消息显示空状态
        if (listLength == 0 && !isLoading) {
          return _buildEmptyState();
        }

        // 消息列表 - 添加下拉刷新和上拉加载
        // ✅ 移除动态ValueKey，避免数据更新时导致列表重建并滚动到顶部
        return RefreshIndicator(
          onRefresh: controller.refreshMessageList,
          child: NotificationListener<ScrollNotification>(
            onNotification: (ScrollNotification scrollInfo) {
              // 上拉加载更多
              if (scrollInfo.metrics.pixels ==
                      scrollInfo.metrics.maxScrollExtent &&
                  hasMoreData &&
                  !isLoading) {
                controller.loadMoreMessages();
              }
              return false;
            },
            child: ListView.builder(
              // ✅ 使用稳定的key，只在tab切换时改变，避免数据更新时重建
              key: ValueKey('list_${selectedTabIndex}'),
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
              itemCount: listLength + (hasMoreData ? 1 : 0),
              itemBuilder: (context, index) {
                // ✅ 在itemBuilder中也访问响应式变量，确保响应式更新
                final currentList = controller.messageList;

                // 显示加载更多指示器
                if (index == currentList.length) {
                  return _buildLoadMoreIndicator();
                }

                final message = currentList[index];
                return _buildMessageItem(message);
              },
            ),
          ),
        );
      }),
    );
  }

  // 构建消息项
  Widget _buildMessageItem(Map<String, dynamic> message) {
    // 获取告警类型
    final alarmType = message['alarmType'] as int? ?? 1;
    // 根据告警类型获取对应图片
    final alarmIcon = alarmTypeIconMap[alarmType] ?? alarmTypeIconMap[1]!;

    return GestureDetector(
      onTap: () async {
        // 点击消息跳转到设备详情页面并选中告警历史
        final hsId = message['hsId']?.toString();
        final deviceId = message['deviceId']?.toString();
        final channelId = message['channelId']?.toString();
        final deviceName =
            message['deviceName']?.toString() ??
            message['channelName']?.toString() ??
            '未知设备';

        // 获取告警视频URL和告警信息
        final alarmVideoUrl = message['alarmVideo']?.toString();
        final alarmId = message['id']?.toString();
        final alarmTime =
            message['time']?.toString() ?? message['alarmTime']?.toString();

        if (hsId != null) {
          // 标记消息为已读
          final msgId = message['id']?.toString();
          if (msgId != null) {
            // ✅ 统一传递deviceId参数，与设备详情页面保持一致
            controller.markMessageRead(msgId, hsId, deviceId: deviceId);
          }

          // 跳转到设备详情页面，选中告警历史tab（索引2）
          await Get.toNamed(
            Routes.DEVICE_DETAIL,
            arguments: {
              'hsId': hsId,
              'deviceId': deviceId ?? '',
              'channelId': channelId ?? '',
              'deviceName': deviceName,
              'initialTab': 2, // 选中告警历史tab
              'alarmVideoUrl': alarmVideoUrl, // 传递告警视频URL
              'targetAlarmId': alarmId, // 传递目标告警ID，用于定位
              'targetAlarmTime': alarmTime, // 传递告警时间，用于设置日期筛选
            },
          );

          // ✅ 返回页面后，刷新未读消息角标
          await controller.refreshUnreadCount();
        } else {
          // 如果缺少必要参数，显示提示
          Get.snackbar('提示', '设备信息不完整，无法跳转');
        }
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 15.h),
        padding: EdgeInsets.all(26.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Column(
          children: [
            // 上半部分：标题和设备信息
            Row(
              children: [
                // 标题左侧的告警图片
                Container(
                  width: 32,
                  height: 32,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Image.asset(
                    'assets/images/message/gaojing.png',
                    width: 32,
                    height: 32,
                    fit: BoxFit.cover,
                  ),
                ),
                SizedBox(width: 12.w),
                Text(
                  '告警信息',
                  style: TextStyle(
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w500,
                    color: const Color(0xFF333333),
                  ),
                ),
                const Spacer(),
                Icon(
                  Icons.videocam_outlined,
                  size: 32.w,
                  color: const Color(0xFF999999).withValues(alpha: 0.6),
                ),
                SizedBox(width: 10.w),
                Text(
                  message['channelName']?.toString() ?? "其他设备",
                  style: TextStyle(
                    fontSize: 26.sp,
                    color: const Color(0xFF666666),
                  ),
                ),
              ],
            ),
            SizedBox(height: 20.h),
            // 分割线
            Container(height: 1, color: const Color(0xFFF0F0F0)),
            SizedBox(height: 20.h),
            // 下半部分：告警信息、时间和视频缩略图
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 告警图片 - 固定32x32，不使用适配（带未读小红点）
                Stack(
                  clipBehavior: Clip.none,
                  children: [
                    Container(
                      width: 32,
                      height: 32,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: Image.asset(
                        alarmIcon,
                        width: 32,
                        height: 32,
                        fit: BoxFit.cover,
                      ),
                    ),
                    // 未读消息小红点标识
                    if ((message['readStatus'] != 1 &&
                            message['readStatus'] != null) ||
                        (message['read'] != true && message['read'] != null))
                      Positioned(
                        top: -4.h,
                        right: -4.w,
                        child: Container(
                          width: 12.w,
                          height: 12.h,
                          decoration: const BoxDecoration(
                            color: Color(0xFFFF0202),
                            shape: BoxShape.circle,
                          ),
                        ),
                      ),
                  ],
                ),
                SizedBox(width: 17.w),
                // 告警信息和时间
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 告警信息
                      Text(
                        message['alarmTypeName']?.toString() ?? '报警消息',
                        style: TextStyle(
                          fontSize: 28.sp,
                          fontWeight: FontWeight.w500,
                          color: const Color(0xFF333333),
                        ),
                      ),
                      SizedBox(height: 12.h),
                      // 时间
                      Text(
                        _formatTime(message['time']?.toString()),
                        style: TextStyle(
                          fontSize: 24.sp,
                          color: const Color(0xFF999999),
                        ),
                      ),
                    ],
                  ),
                ),
                // 视频缩略图 - 如果有联动快照则显示，否则显示占位图
                Builder(
                  builder: (context) {
                    // 尝试多个可能的字段名
                    final pictureUrl = message['alarmPicture']?.toString() ??
                        message['picUrl']?.toString() ??
                        message['picture']?.toString() ??
                        '';
                    
                    return Container(
                      width: 212.w,
                      height: 142.h,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(16.r),
                        color: const Color(0xFFF0F0F0),
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(16.r),
                        child: pictureUrl.isNotEmpty
                            ? Stack(
                                children: [
                                  Image.network(
                                    pictureUrl,
                                    width: double.infinity,
                                    height: double.infinity,
                                    fit: BoxFit.cover,
                                    errorBuilder: (context, error, stackTrace) {
                                      return Image.asset(
                                        'assets/images/暂无视频2x.png',
                                        width: double.infinity,
                                        height: double.infinity,
                                        fit: BoxFit.cover,
                                      );
                                    },
                                  ),
                                  Center(
                                    child: Container(
                                      width: 44.w,
                                      height: 44.h,
                                      decoration: BoxDecoration(
                                        color: Colors.black.withValues(alpha: 0.5),
                                        shape: BoxShape.circle,
                                      ),
                                      child: Icon(
                                        Icons.play_arrow,
                                        color: Colors.white,
                                        size: 24.w,
                                      ),
                                    ),
                                  ),
                                ],
                              )
                            : Image.asset(
                                'assets/images/暂无视频2x.png',
                                width: double.infinity,
                                height: double.infinity,
                                fit: BoxFit.cover,
                              ),
                      ),
                    );
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 空状态
  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 空状态图片
          Image.asset('assets/images/null.png', width: 378.w, height: 378.w),
          SizedBox(height: 40.w),
          Text(
            '暂无消息',
            style: TextStyle(fontSize: 28.sp, color: const Color(0xFF999999)),
          ),
        ],
      ),
    );
  }

  // 加载更多指示器
  Widget _buildLoadMoreIndicator() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 20.h),
      child: Center(
        child: Obx(
          () =>
              controller.isLoading.value
                  ? SizedBox(
                    width: 20.w,
                    height: 20.h,
                    child: const CircularProgressIndicator(strokeWidth: 2),
                  )
                  : Text(
                    '已加载全部消息',
                    style: TextStyle(
                      fontSize: 24.sp,
                      color: const Color(0xFF999999),
                    ),
                  ),
        ),
      ),
    );
  }

  // 显示日期选择器
  void _showDatePicker() {
    DateTime tempSelectedDate = controller.selectedDate.value;

    Get.bottomSheet(
      Container(
        height: 520.h,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(24.r),
            topRight: Radius.circular(24.r),
          ),
        ),
        child: Column(
          children: [
            // 顶部标题栏
            Container(
              height: 100.h,
              padding: EdgeInsets.symmetric(horizontal: 32.w),
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                  bottom: BorderSide(color: const Color(0xFFE0E0E0), width: 1),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: () => Get.back(),
                    child: Text(
                      '取消',
                      style: TextStyle(
                        fontSize: 34.sp,
                        color: const Color(0xFF127FFF),
                      ),
                    ),
                  ),
                  Text(
                    '选择日期',
                    style: TextStyle(
                      fontSize: 34.sp,
                      fontWeight: FontWeight.w600,
                      color: const Color(0xFF333333),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      controller.setDateFilter(tempSelectedDate);
                      Get.back();
                    },
                    child: Text(
                      '确定',
                      style: TextStyle(
                        fontSize: 34.sp,
                        color: const Color(0xFF127FFF),
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            // 日期选择器
            Expanded(
              child: Container(
                color: Colors.white,
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.date,
                  initialDateTime: controller.selectedDate.value,
                  minimumDate: DateTime(2020, 1, 1),
                  maximumDate: DateTime.now(),
                  onDateTimeChanged: (DateTime date) {
                    tempSelectedDate = date;
                  },
                  dateOrder: DatePickerDateOrder.ymd,
                ),
              ),
            ),
            // 清除筛选按钮
            if (controller.isDateFilterEnabled.value)
              Container(
                padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 16.h),
                child: GestureDetector(
                  onTap: () {
                    controller.clearDateFilter();
                    Get.back();
                  },
                  child: Container(
                    width: double.infinity,
                    height: 88.h,
                    decoration: BoxDecoration(
                      color: const Color(0xFFF5F5F5),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Center(
                      child: Text(
                        '清除筛选',
                        style: TextStyle(
                          fontSize: 32.sp,
                          color: const Color(0xFF999999),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
          ],
        ),
      ),
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
    );
  }

  // 格式化时间 - 显示年月日时分秒格式
  String _formatTime(String? timeStr) {
    if (timeStr == null || timeStr.isEmpty) return '';

    try {
      final dateTime = DateTime.parse(timeStr);
      // 转换为北京时间 (UTC+8)
      final beijingTime = dateTime.toUtc().add(const Duration(hours: 8));
      // 格式化为 yyyy-MM-dd HH:mm:ss 格式
      return '${beijingTime.year}-${beijingTime.month.toString().padLeft(2, '0')}-${beijingTime.day.toString().padLeft(2, '0')} ${beijingTime.hour.toString().padLeft(2, '0')}:${beijingTime.minute.toString().padLeft(2, '0')}:${beijingTime.second.toString().padLeft(2, '0')}';
    } catch (e) {
      // 如果解析失败，返回原始格式
      return timeStr;
    }
  }
}
